#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
//gcc -lpthread
#define NUMBER_THREADS 5 

void* handler_thread(void* thread_num){
    int i=(int)thread_num;
    printf("in thread %d\n",i);
    printf("%ld\n",pthread_self());
    int* result=(int*)malloc(sizeof(int));
    *result=2*i;
    pthread_exit((void*)result);
}


int main(void){
    pthread_t tid=-1;
    pthread_t threads[NUMBER_THREADS]={0};

    for(int i = 0;i < NUMBER_THREADS;i++){
        printf("creat thread %d\n",i);
        if(pthread_create(&threads[i],NULL,handler_thread,(void*)i) != 0){
            perror("pthread_create err");
            return -1;
        }
    }
    
    
    printf("in main before\n");

    void* thread_result = NULL;
    for(int i = 0;i < NUMBER_THREADS;i++){
        int rc =pthread_join(threads[i],&thread_result);
        if(rc){
            printf("error:return code pthread err %d\n",i);
        }
        printf("i = %d, result = %d\n",i,*(int*)thread_result);
        free(thread_result);
        thread_result=NULL;
    }
    
    printf("in main\n");

    return 0;
}